import React, { Suspense, useEffect, useState, lazy } from 'react'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import useUserStore from '@/store/user'
import { AuthRoute } from '@/components/AuthRoute'
// import { getUserMenus } from '@/api/permission'
import { message, Spin } from 'antd'

// 定义API响应类型
interface ApiResponse<T> {
  code: number
  message: string
  data: T
  isSuc: boolean
}

// 用户信息类型
interface UserInfo {
  userId: number
  userName: string
  loginName: string
  gender: string
  phone: string
  token: string
  [key: string]: any
}

// 菜单项类型
interface MenuItem {
  id: number
  title: string
  icon: string
  path: string
  name: string
  filePath: string | null
  parentId: number
  children: MenuItem[]
}

// 懒加载组件
const Login = lazy(() => import('@/views/login/Index'))
const Home = lazy(() => import('@/views/home/Index'))
const Layout = lazy(() => import('@/views/layout/Index'))
const Error = lazy(() => import('@/views/error/Index'))
const Product = lazy(() => import('@/views/product/Index'))
const ProductLabel = lazy(() => import('@/views/product/ProductLabel'))
const Brand = lazy(() => import('@/views/brand/Index'))
const Good = lazy(() => import('@/views/good/Index'))
const Order = lazy(() => import('@/views/order/Index'))
const Permission = lazy(() => import('@/views/permission/Index'))
const Role = lazy(() => import('@/views/role/Index'))
const User = lazy(() => import('@/views/user/Index'))
const BoxType = lazy(() => import('@/views/boxType/Index'))
const BoxTypeDialog = lazy(() => import('@/views/boxType/BoxTypeDialog'))


function App() {
  const { userInfo } = useUserStore()
  const [router, setRouter] = useState<ReturnType<typeof createBrowserRouter>>()
  const [loading, setLoading] = useState<boolean>(true)

  // 创建基础路由
  const createBaseRoutes = () => {
    return [
      {
        path: '/login',
        element: <Login />
      },
      {
        path: '/',
        element: <AuthRoute><Layout /></AuthRoute>,
        children: [
          {
            index: true,
            element: (
              <AuthRoute>
                <Home />
              </AuthRoute>
            )
          },
          // 静态路由配置
          {
            path: 'product',
            element: (
              <AuthRoute>
                <Product />
              </AuthRoute>
            )
          },
          {
            path: 'product/label/:id',
            element: (
              <AuthRoute>
                <ProductLabel />
              </AuthRoute>
            )
          },
          // 预定义的路由映射
          {
            path: 'brandList',
            element: (
              <AuthRoute>
                <Brand />
              </AuthRoute>
            )
          },
          {
            path: 'goodList',
            element: (
              <AuthRoute>
                <Good />
              </AuthRoute>
            )
          },
          {
            path: 'orderList',
            element: (
              <AuthRoute>
                <Order />
              </AuthRoute>
            )
          },
          {
            path: 'permissionList',
            element: (
              <AuthRoute>
                <Permission />
              </AuthRoute>
            )
          },
          {
            path: 'roleList',
            element: (
              <AuthRoute>
                <Role />
              </AuthRoute>
            )
          },
          {
            path: 'userList',
            element: (
              <AuthRoute>
                <User />
              </AuthRoute>
            )
          },{
            path: 'boxType',
            element: (
              <AuthRoute>
                <BoxType />
              </AuthRoute>
            )
          },{
            path: 'boxTypeDialog',
            element: (
              <AuthRoute>
                <BoxTypeDialog visible={true} boxType={null} onCancel={() => {}} onConfirm={() => {}} />
              </AuthRoute>
            )
          }
        ]
      },
      {
        path: '*',
        element: <Error />
      }
    ]
  }

  useEffect(() => {
    // 初始化路由
    const baseRoutes = createBaseRoutes()
    setRouter(createBrowserRouter(baseRoutes))
    setLoading(false)

    // 注释掉动态路由加载
    // 如果用户已登录，加载动态菜单
    // if (userInfo?.userId) {
    //   // 加载动态路由
    //   const loadDynamicRoutes = async () => {
    //     if (!userInfo?.userId) return
    //
    //     setLoading(true)
    //     try {
    //       const res = await getUserMenus(userInfo.userId) as ApiResponse<MenuItem[]>
    //       if (res.isSuc && res.data) {
    //         console.log('获取到的菜单数据:', res.data)
    //         const menuItems = res.data
    //         const dynamicRoutes = generateRoutesFromMenus(menuItems)
    //         
    //         // 创建新的路由配置
    //         const baseRoutes = createBaseRoutes()
    //         
    //         // 将动态路由添加到基础路由的children中
    //         if (baseRoutes[1] && baseRoutes[1].children) {
    //           baseRoutes[1].children = [
    //             ...baseRoutes[1].children,
    //             ...dynamicRoutes
    //           ]
    //         }
    //
    //         // 更新路由
    //         setRouter(createBrowserRouter(baseRoutes))
    //       } else {
    //         console.error('获取菜单失败:', res.message)
    //         message.error('获取菜单失败: ' + res.message)
    //       }
    //     } catch (error) {
    //       console.error('加载动态路由出错:', error)
    //       message.error('加载动态路由出错')
    //     } finally {
    //       setLoading(false)
    //     }
    //   }
    //
    //   loadDynamicRoutes()
    // }
  }, [userInfo])

  // 从菜单生成路由配置 - 注释掉
  // const generateRoutesFromMenus = (menuItems: MenuItem[]): any[] => {
  //   const routes: any[] = []
  //
  //   const processMenuItem = (item: MenuItem) => {
  //     // 如果有path和filePath，创建路由
  //     if (item.path && item.filePath) {
  //       try {
  //         // 根据filePath动态导入组件
  //         const componentPath = `./views/${item.filePath}/Index`
  //         console.log('尝试加载组件:', componentPath)
  //         
  //         // 创建路由配置
  //         routes.push({
  //           path: item.path,
  //           element: (
  //             <AuthRoute>
  //               {/* 根据filePath选择对应的组件 */}
  //               {item.filePath === 'brand' ? <Brand /> :
  //                item.filePath === 'good' ? <Good /> :
  //                item.filePath === 'order' ? <Order /> :
  //                item.filePath === 'permission' ? <Permission /> :
  //                item.filePath === 'role' ? <Role /> :
  //                item.filePath === 'user' ? <User /> :
  //                <div>组件 {item.filePath} 不存在</div>}
  //             </AuthRoute>
  //           )
  //         })
  //       } catch (error) {
  //         console.error(`无法加载组件: ./views/${item.filePath}/Index`, error)
  //       }
  //     }
  //
  //     // 递归处理子菜单
  //     if (item.children && item.children.length > 0) {
  //       item.children.forEach((child: MenuItem) => {
  //         processMenuItem(child)
  //       })
  //     }
  //   }
  //
  //   // 处理所有菜单项
  //   menuItems.forEach((item: MenuItem) => {
  //     processMenuItem(item)
  //   })
  //
  //   return routes
  // }

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" tip="加载应用中..." />
      </div>
    )
  }

  return (
    <Suspense fallback={
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" tip="加载页面中..." />
      </div>
    }>
      {router && <RouterProvider router={router} />}
    </Suspense>
  )
}

export default App
